package com.yinhai.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;

import com.lz.util.Utils;

public class SMSService extends Service {
	
	private Context thisRef;
	
	private Handler handler1 = new Handler();
	private boolean isRun = false;
	Map<String,Object> map = new HashMap<String,Object>();   
	
	@Override
	public void onCreate() {
		super.onCreate();
		thisRef = this;
		
		Log.i("tag", "zi dong hui fu duan xin Service Create");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		 
		if(!isRun){
			isRun = true;
			handler1.postDelayed(msgTask, 1000);
		}
		Log.i("tag", "zi dong hui fu duan xin Service Start");
		return super.onStartCommand(intent, flags, startId);
	}
	
	
	@Override
	public void onDestroy() {
		isRun = false;
		Log.i("tag", "zi dong hui fu duan xin Service Stop");
		handler1.removeCallbacks(msgTask);
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 短信
	 * */
    private Runnable msgTask = new Runnable() {  
        public void run() { 
        	
        	List<String> name =getSmsInPhone();
        	
        		try {
        			for(int i = 0 ; i<name.size();i++){
        				String [] n = name.get(i).split(",");
        				if( Long.parseLong(n[1]) > Utils.getFSDATE(thisRef)){
        					//ti = Long.parseLong(n[1]);
        					Utils.SaveFSDATE(thisRef, Long.parseLong(n[1]));
        					if(map.get(n[0]) == null){
        						map.put(n[0], n[1]); // 有值  表示已发送
        						//Log.i("-=====",n[0] +""+Utils.getDXContent(thisRef));
        						String sms_content =Utils.getDXContent(thisRef);
        						String phone_number = n[0];
            					//发送短信
        						SmsManager smsManager = SmsManager.getDefault();
        	                    //if(sms_content.length() > 70) {
        	                        List<String> contents = smsManager.divideMessage(sms_content);
        	                        for(String sms : contents) {
        	                            smsManager.sendTextMessage(phone_number, null, sms, null, null);
        	                            ContentValues values = new ContentValues();
        								// 发送时间
        								values.put("date", System.currentTimeMillis());
        								// 阅读状态
        								values.put("read", 0);
        								// 1为收 2为发
        								values.put("type", 2);
        								// 送达号码
        								values.put("address", phone_number);
        								// 送达内容
        								values.put("body", sms_content);
        								// 插入短信库
        								getContentResolver()
        										.insert(Uri.parse("content://sms/sent"),
        												values);
        	                        }
    							
        	                   /* } else {
        	                     smsManager.sendTextMessage(phone_number, null, sms_content, null, null);
        	                    }*/
            				}else{
            					/*if(Long.parseLong(map.get(n[0])+"") > Utils.getFSDATE(thisRef) ){
            						map.remove(map.get(n[0]));
            					}*/
            				}
        					
        				}else{
        					//不处理
        					//Log.i("========", "xxxxxxx");
        				}
        					
        			}
        			if(isRun){
        				handler1.postDelayed(msgTask, 10*1000);
        			}
        		} catch (Exception e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        }
    };
    
    public List<String> getSmsInPhone()   
	{   
		List<String>  list = new ArrayList<String>();
		
	    final String SMS_URI_ALL   = "content://sms/";     
	    try{ 
	    	Long t  =  Utils.getKSDATE(thisRef);//开始日期
	    	Long t2 = Utils.getJSDATE(thisRef);//结束日期
	    	//Log.i("=========", t+"======="+t2);
	    	if(t !=0 && t<t2){
	    		ContentResolver cr = getContentResolver();   
	 	        String[] projection = new String[]{"_id", "address", "person",    
	 	                "body", "date", "type"};    //type 1 为接收的短信  2 发送的短信
	 	        Uri uri = Uri.parse(SMS_URI_ALL);   
	 	        String where = "date > "+t+" and date < "+t2+" and type=1";  
	 	        Cursor cur = cr.query(uri, projection, where, null, "date");   
	 	  
	 	        if (cur.moveToFirst()) {   
	 	            String phoneNumber;          
	 	            int phoneNumberColumn = cur.getColumnIndex("address");   
	 	            int dateColumn = cur.getColumnIndex("date");   
	 	            do{   
	 	                phoneNumber = cur.getString(phoneNumberColumn);   
	 	                String name =phoneNumber+","+cur.getString(dateColumn);
	 	                list.add(name);
	 	            }while(cur.moveToNext());   
	 	        } else {   
	 	        }   
	    	}
	            
	    } catch(Exception ex) {
	    	 ex.printStackTrace();
	         Log.d("SQLiteException in getSmsInPhone", ex.getMessage()); 
	    }   
	    return list;   
	}
    
}
